package com.lyc.lojbackendquestionservice.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.shaded.com.google.common.util.concurrent.RateLimiter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.lyc.lojbackendcommon.annotation.AuthCheck;
import com.lyc.lojbackendcommon.common.BaseResponse;
import com.lyc.lojbackendcommon.common.DeleteRequest;
import com.lyc.lojbackendcommon.common.ErrorCode;
import com.lyc.lojbackendcommon.common.ResultUtils;
import com.lyc.lojbackendcommon.constant.UserConstant;
import com.lyc.lojbackendcommon.exception.BusinessException;
import com.lyc.lojbackendcommon.exception.ThrowUtils;
import com.lyc.lojbackendmodel.model.codesandbox.JudgeInfo;
import com.lyc.lojbackendmodel.model.dto.question.*;
import com.lyc.lojbackendmodel.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.lyc.lojbackendmodel.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.lyc.lojbackendmodel.model.dto.questionsubmit.QuestionSubmitResultData;
import com.lyc.lojbackendmodel.model.dto.questionsubmit.QuestionSubmitTestRequest;
import com.lyc.lojbackendmodel.model.entity.Question;
import com.lyc.lojbackendmodel.model.entity.QuestionSubmit;
import com.lyc.lojbackendmodel.model.entity.User;
import com.lyc.lojbackendmodel.model.enums.QuestionSubmitLanguageEnum;
import com.lyc.lojbackendmodel.model.enums.QuestionSubmitStatusEnum;
import com.lyc.lojbackendmodel.model.vo.QuestionManageVO;
import com.lyc.lojbackendmodel.model.vo.QuestionSubmitVO;
import com.lyc.lojbackendmodel.model.vo.QuestionVO;
import com.lyc.lojbackendquestionservice.manage.RedissonLimiter;
import com.lyc.lojbackendquestionservice.service.QuestionService;
import com.lyc.lojbackendquestionservice.service.QuestionSubmitService;
import com.lyc.lojbackendserviceclient.service.UserFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * 题目接口

 */
@RestController
@RequestMapping("/")
@Slf4j
public class QuestionController {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserFeignClient userFeignClient;
    
    @Resource
    private QuestionSubmitService questionSubmitService;

    private final static Gson GSON = new Gson();

    /**
     * 创建
     *
     * @param questionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addQuestion(@RequestBody QuestionAddRequest questionAddRequest, HttpServletRequest request) {
        if (questionAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionAddRequest, question);
        List<String> tags = questionAddRequest.getTags();
        if (tags != null) {
            question.setTags(GSON.toJson(tags));
        }
        List<JudgeCase> judgeCase = questionAddRequest.getJudgeCase();
        if (judgeCase != null) {
            question.setJudgeCase(GSON.toJson(judgeCase));
        }
        JudgeConfig judgeConfig = questionAddRequest.getJudgeConfig();
        if (judgeConfig != null) {
            question.setJudgeConfig(GSON.toJson(judgeConfig));
        }
        questionService.validQuestion(question, true);
        User loginUser = userFeignClient.getLoginUser(request);
        question.setUserId(loginUser.getId());
        question.setFavourNum(0);
        question.setThumbNum(0);
        boolean result = questionService.save(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newQuestionId = question.getId();
        return ResultUtils.success(newQuestionId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userFeignClient.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestion.getUserId().equals(user.getId()) && !userFeignClient.isAdmin(user)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = questionService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param questionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateQuestion(@RequestBody QuestionUpdateRequest questionUpdateRequest) {
        if (questionUpdateRequest == null || questionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionUpdateRequest, question);
        List<String> tags = questionUpdateRequest.getTags();
        if (tags != null) {
            question.setTags(GSON.toJson(tags));
        }
        List<JudgeCase> judgeCase = questionUpdateRequest.getJudgeCase();
        if (judgeCase != null) {
            question.setJudgeCase(GSON.toJson(judgeCase));
        }
        JudgeConfig judgeConfig = questionUpdateRequest.getJudgeConfig();
        if (judgeConfig != null) {
            question.setJudgeConfig(GSON.toJson(judgeConfig));
        }
        // 参数校验
        questionService.validQuestion(question, false);
        long id = questionUpdateRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = questionService.updateById(question);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取 (脱敏)
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Question> getQuestionById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = questionService.getById(id);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        User loginUser = userFeignClient.getLoginUser(request);
        if (!question.getUserId().equals(loginUser.getId()) && !userFeignClient.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return ResultUtils.success(question);
    }
    
    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<QuestionVO> getQuestionVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = questionService.getById(id);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(questionService.getQuestionVO(question, request));
    }

    /**
     * 获取上一题
     * @param questionId
     * @param request
     * @return
     */
    @GetMapping("/get/vo/previous")
    public BaseResponse<QuestionVO> getPreviousQuestion(long questionId, HttpServletRequest request) {
        if (questionId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取比当前id还小并且离的最近的id
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.lt("id", questionId).orderByDesc("id").last("LIMIT 1");
        Question question = questionService.getOne(queryWrapper);
//        Question question = questionService.getById(preQuestionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(questionService.getQuestionVO(question, request));
    }

    /**
     * 获取下一题
     * @param questionId
     * @param request
     * @return
     */
    @GetMapping("/get/vo/next")
    public BaseResponse<QuestionVO> getNextQuestion(long questionId, HttpServletRequest request) {
        if (questionId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("id", questionId).orderByAsc("id").last("LIMIT 1");
        Question question = questionService.getOne(queryWrapper);
//        Question question = questionService.getById(id);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(questionService.getQuestionVO(question, request));
    }

    /**
     * 随机获取题目
     * @param questionId
     * @param request
     * @return
     */
    @GetMapping("/get/vo/random")
    public BaseResponse<QuestionVO> getRandomQuestionVO(long questionId, HttpServletRequest request) {
        if (questionId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 设置 QueryWrapper，排除给定的 questionId
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("id", questionId);
        // 计算总题目数（不包括给定的 questionId）
        List<Question> questionList = questionService.list(queryWrapper);
        if(questionList.isEmpty()){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        int randomIndex = ThreadLocalRandom.current().nextInt(questionList.size());
        Question question = questionList.get(randomIndex);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(questionService.getQuestionVO(question, request));
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
/*    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                               HttpServletRequest request) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest, request));
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }*/

    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                               HttpServletRequest request) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        QueryWrapper<Question> queryWrapper = questionService.getQueryWrapper(questionQueryRequest, request);
        if (queryWrapper != null) {
            Page<Question> questionPage = questionService.page(new Page<>(current, size), queryWrapper);
            List<QuestionVO> records = questionPage.getRecords().stream()
                    .map(question -> questionService.getQuestionVO(question, request))
                    .collect(Collectors.toList());
            Page<QuestionVO> page = new Page<>(current, size, questionPage.getTotal());
            page.setRecords(records);
            return ResultUtils.success(page);
        }else{
            Page<QuestionVO> page = new Page<>(current, size, 0);
            return ResultUtils.success(page);
        }
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listMyQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                                 HttpServletRequest request) {
        if (questionQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userFeignClient.getLoginUser(request);
        questionQueryRequest.setUserId(loginUser.getId());
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest, request));
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }
    
    /**
     * 编辑（题目）
     *
     * @param questionEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editQuestion(@RequestBody QuestionEditRequest questionEditRequest, HttpServletRequest request) {
        if (questionEditRequest == null || questionEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionEditRequest, question);
        List<String> tags = questionEditRequest.getTags();
        if (tags != null) {
            question.setTags(GSON.toJson(tags));
        }
        List<JudgeCase> judgeCase = questionEditRequest.getJudgeCase();
        if (judgeCase != null) {
            question.setJudgeCase(GSON.toJson(judgeCase));
        }
        JudgeConfig judgeConfig = questionEditRequest.getJudgeConfig();
        if (judgeConfig != null) {
            question.setJudgeConfig(GSON.toJson(judgeConfig));
        }
        // 参数校验
        questionService.validQuestion(question, false);
        User loginUser = userFeignClient.getLoginUser(request);
        long id = questionEditRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldQuestion.getUserId().equals(loginUser.getId()) && !userFeignClient.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = questionService.updateById(question);
        return ResultUtils.success(result);
    }

    //获取编程语言
    @GetMapping("/get/language")
    public BaseResponse<List<String>> getCodeLanguage() {
        return ResultUtils.success(QuestionSubmitLanguageEnum.getValues());
    }

    /**
     * 分页获取题目列表（除了管理员外，普通用户只能看到非答案，提交代码等公开信息）
     *
     * @param questionSubmitQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/question_submit/list/page")
    public BaseResponse<Page<QuestionSubmitVO>> listQuestionSubmitByPage(@RequestBody QuestionSubmitQueryRequest questionSubmitQueryRequest,
                                                                         HttpServletRequest request) {
        long current = questionSubmitQueryRequest.getCurrent();
        long size = questionSubmitQueryRequest.getPageSize();
        //从数据库中查询原始的题目提交分页信息
        Page<QuestionSubmit> questionSubmitPage = questionSubmitService.page(new Page<>(current, size), questionSubmitService.getQueryWrapper(questionSubmitQueryRequest));
        //返回脱敏信息
        User loginUser = userFeignClient.getLoginUser(request);
        return ResultUtils.success(questionSubmitService.getQuestionSubmitVOPage(questionSubmitPage, loginUser));
    }
    
    /**
     * 分页获取题目列表（仅管理员）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<QuestionManageVO>> listQuestionByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                                   HttpServletRequest request) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        //从数据库中查询原始的题目提交分页信息
        Page<Question> questionPage = questionService.page(new Page<>(current, size), questionService.getQueryWrapper(questionQueryRequest, request));
        //返回脱敏信息
        User loginUser = userFeignClient.getLoginUser(request);
        return ResultUtils.success(
                questionService.getQuestionManageVOPage(questionPage, loginUser)
        );
    }

    // 谷歌的guava组件限流
    private final RateLimiter rateLimiter = RateLimiter.create(2.0); // 每秒最多允许2个请求

    // RedissionLimiter 限流, 业务端限流
    @Resource
    private RedissonLimiter redissonLimiter;

    /**
     * 提交题目
     *
     * @param questionSubmitAddRequest
     * @param request
     * @return 题目提交记录的 id
     */
    @PostMapping("/question_submit/do")
    public BaseResponse<QuestionSubmitResultData> doQuestionSubmit(@RequestBody QuestionSubmitAddRequest questionSubmitAddRequest,
                                               HttpServletRequest request) {
        if (questionSubmitAddRequest == null || questionSubmitAddRequest.getQuestionId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        final User loginUser = userFeignClient.getLoginUser(request);
        /*        // 实现限流
        // 尝试获取许可，如果没有许可则等待，直到有足够的许可为止
        // rateLimiter.acquire();
        // 尝试获取许可，如果没有许可则等待，直到有足够的许可为止
        if (!rateLimiter.tryAcquire()) {
            throw new BusinessException(ErrorCode.REQUEST_LIMIT_EXCEEDED);
        }*/
        boolean rateLimit = redissonLimiter.doRateLimit(loginUser.getId().toString());
        if (!rateLimit) {
            return ResultUtils.error(ErrorCode.REQUEST_LIMIT_EXCEEDED, "提交过于频繁,请稍后重试");
        }
        long questionSubmitId = questionSubmitService.doQuestionSubmit(questionSubmitAddRequest, loginUser);
        QuestionSubmitResultData questionSubmitResultData = new QuestionSubmitResultData();

        boolean isJudgeCompleted = false;
        long startTime = System.currentTimeMillis();
        QuestionSubmit questionSubmit = null;
        // 轮询判断
        while (!isJudgeCompleted) {
            // 检查判题是否已完成的逻辑
            questionSubmit = questionSubmitService.getById(questionSubmitId);
            Integer status = questionSubmit.getStatus();
            if(status.equals(QuestionSubmitStatusEnum.SUCCEED.getValue()) || status.equals(QuestionSubmitStatusEnum.FAILED.getValue())){
                isJudgeCompleted = true;
            }
            // 如果超过指定的等待时间，可以选择抛出异常或执行其他操作
            if (!isJudgeCompleted && System.currentTimeMillis() - startTime > 5000) {
                throw new BusinessException(ErrorCode.TIMEOUT_ERROR, "等待判题超时");
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        String judgeInfoStr = questionSubmit.getJudgeInfo();
        JudgeInfo judgeInfo = JSONUtil.toBean(judgeInfoStr, JudgeInfo.class);
        String message = judgeInfo.getMessage();
        String detailError = questionSubmit.getDetailError();
        Long time = judgeInfo.getTime();
        Long memory = judgeInfo.getMemory();
        questionSubmitResultData.setResult(message);
        questionSubmitResultData.setMessage(detailError);
        questionSubmitResultData.setTime(time);
        questionSubmitResultData.setMemory(memory);
        return ResultUtils.success(questionSubmitResultData);
    }
    
    /**
     * 题目测试（用户输入测试用例）
     * @param questionSubmitTestRequest
     * @param request
     * @return
     */
    @PostMapping("/question_submit/test")
    public BaseResponse<QuestionSubmitResultData> doQuestionSubmitTest(@RequestBody QuestionSubmitTestRequest questionSubmitTestRequest,
                                               HttpServletRequest request) {
        if (questionSubmitTestRequest == null || questionSubmitTestRequest.getQuestionId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        final User loginUser = userFeignClient.getLoginUser(request);
        boolean rateLimit = redissonLimiter.doRateLimit(loginUser.getId().toString());
        if (!rateLimit) {
            return ResultUtils.error(ErrorCode.REQUEST_LIMIT_EXCEEDED, "提交过于频繁,请稍后重试");
        }
        long questionSubmitId = questionSubmitService.doQuestionSubmitTest(questionSubmitTestRequest, loginUser);
        QuestionSubmitResultData questionSubmitResultData = new QuestionSubmitResultData();
        boolean isJudgeCompleted = false;
        long startTime = System.currentTimeMillis();
        QuestionSubmit questionSubmit = null;
        // 轮询判断
        while (!isJudgeCompleted) {
            // 检查判题是否已完成的逻辑
            questionSubmit = questionSubmitService.getById(questionSubmitId);
            Integer status = questionSubmit.getStatus();
            if(status.equals(QuestionSubmitStatusEnum.SUCCEED.getValue()) || status.equals(QuestionSubmitStatusEnum.FAILED.getValue())){
                isJudgeCompleted = true;
            }
            // 如果超过指定的等待时间，可以选择抛出异常或执行其他操作
            if (!isJudgeCompleted && System.currentTimeMillis() - startTime > 5000) {
                throw new BusinessException(ErrorCode.TIMEOUT_ERROR, "等待判题超时");
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        String judgeInfoStr = questionSubmit.getJudgeInfo();
        JudgeInfo judgeInfo = JSONUtil.toBean(judgeInfoStr, JudgeInfo.class);
        String message = judgeInfo.getMessage();
        String detailError = questionSubmit.getDetailError();
        Long time = judgeInfo.getTime();
        Long memory = judgeInfo.getMemory();
        questionSubmitResultData.setResult(message);
        questionSubmitResultData.setMessage(detailError);
        questionSubmitResultData.setTime(time);
        questionSubmitResultData.setMemory(memory);
        return ResultUtils.success(questionSubmitResultData);
    }

    /**
     * 题目推荐
     * @return
     */
    @GetMapping("/recommend")
    public BaseResponse<List<QuestionVO>> getRecommendQuestion(Long questionId, HttpServletRequest request) {
        return ResultUtils.success(questionService.getRecommend(questionId, request));
    }
}
